from flask_sock import Sock
from simple_websocket.ws import Server
from module.aaa_example import example
from flask_socketio import join_room, leave_room
from web_app import socketio

example_sk = Sock(example)


# 前端和后端的socket关闭,此线程也会自动关闭
@example_sk.route("/Sock")
def example_Sock(ws: Server):
    while ws.connected:
        data = ws.receive()
        ws.send("websocket")
        print("data:", data)
    print("ws close")
    ws.close()


# socketio连接时调用,添加namespace表示只有/example/socketio的url才调用
@socketio.on("connect", namespace="/example/socketio")
def on_connect():
    print("connected")


# socketio断开时调用
@socketio.on("disconnect", namespace="/example/socketio")
def on_disconnect():
    print("disconnected")


# socketio收到自定义message消息时调用,msg可以是字符串或者系列化的二进制
# namespace是url的后缀,http://127.0.0.1/example/socketio会调用该函数
@socketio.on("message", namespace="/example/socketio")
def on_connect(msg):
    print("message:", msg)
    socketio.emit("message", msg, namespace="/example/socketio")


# 添加房间,可以把几个人放在一个房间组成群聊,namespace包含多个room,room包含多个socket
@socketio.on("join", namespace="/example/socketio")
def on_join(data):
    username = data["username"]
    room = data["room"]
    join_room(room)
    print(f"{username} has joined the room {room}")
    socketio.emit(
        "join_room",
        f"{username} has joined the room {room}",
        namespace="/example/socketio",
        room=room,
    )


# 离开房间
@socketio.on("leave", namespace="/example/socketio")
def on_leave(data):
    username = data["username"]
    room = data["room"]
    leave_room(room)
    print(f"{username} has left the room {room}")
    socketio.emit(
        "leave_room",
        f"{username} has left the room {room}",
        namespace="/example/socketio",
        room=room,
    )
